<template>
	<view>
		<cu-custom :bgImage="bgImage" topTitle="签字" :needBack="true" backIconColor="#ffffff"
			titleClass="commTitle white"></cu-custom>
		<view class="mt_40">
			<view class="footer flex fz_30 text-center">
				<view class="left" @click="clear">撤销</view>
				<view class="right " @click="finish">确定</view>
			</view>
			<!-- <view class="title">请在下面输入签名：</view> -->
			<canvas class="mycanvas" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove"
				@touchend="touchend" :style="{height: windowHeight + 'px',width: windowWidth + 'px'}"></canvas>

		</view>
	</view>

</template>

<script>
	import baseUrl from "@/api/baseUrl.js";
	import { saveDeclarationInfo,saveDeclarationInfo2,getSignCommitmentLetter} from "@/api/report.js";
	var x = 20;
	var y = 20;
	export default {
		data() {
			return {
				ctx: '', //绘图图像
				points: [], //路径点集合
				isDraw: false,
				windowHeight: '',
				windowWidth: '',
				agreement: '',
				signImage: '',
				flag: true,
				bgImage: require('../../static/images/home/home_header.png'),
				form: {},
				isEdit:1
			};
		},
		// props: {
		//   info: {
		//     type: Object
		//   }
		// },
		onLoad(options) {
			this.windowWidth = uni.getSystemInfoSync().windowWidth
			this.windowHeight = uni.getSystemInfoSync().windowHeight / 5 * 4
			this.ctx = uni.createCanvasContext('mycanvas', this); //创建绘图对象
			this.form = JSON.parse(options.form)
			this.isEdit = options.isEdit
			console.log(this.form)
			//设置画笔样式
			this.ctx.lineWidth = 4;
			this.ctx.lineCap = 'round';
			this.ctx.lineJoin = 'round';
		},
		mounted() {

		},
		onShow() {
			this.flag = true
		},
		methods: {
			//触摸开始，获取到起点
			touchstart: function(e) {
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {
					X: startX,
					Y: startY
				};
				this.points.push(startPoint);
				//每次触摸开始，开启新的路径
				this.ctx.beginPath();
				this.isDraw = true
			},

			//触摸移动，获取到路径点
			touchmove: function(e) {
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					X: moveX,
					Y: moveY
				};
				this.points.push(movePoint); //存点
				let len = this.points.length;
				if (len >= 2) {
					this.draw(); //绘制路径
				}
			},

			// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
			touchend: function() {
				this.points = [];
			},

			/* ***********************************************
			#   绘制笔迹
			#	1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			#	2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			#	3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			************************************************ */
			draw: function() {
				let point1 = this.points[0];
				let point2 = this.points[1];
				this.points.shift();
				this.ctx.moveTo(point1.X, point1.Y);
				this.ctx.lineTo(point2.X, point2.Y);
				this.ctx.stroke();
				this.ctx.draw(true);
			},

			//清空画布
			clear: function() {
				let that = this;
				uni.getSystemInfo({
					success: function(res) {
						let canvasw = res.windowWidth;
						let canvash = res.windowHeight;
						that.ctx.clearRect(0, 0, canvasw, canvash);
						that.ctx.draw(true);
					}
				});
				this.isDraw = false
			},
			aaa() {
				uni.navigateTo({
					url: '/pages/profile/signAgreement/signResult?isSuccess=0'
				})
			},

			//完成绘画并保存到本地
			async finish() {
				let token =  uni.getStorageSync('access_token');
				const that = this;
				if (!this.flag) {
					setTimeout(() => {
						this.flag = true
					}, 5000)
					return false
				}
				if (this.isDraw) {
					this.flag = false
					uni.canvasToTempFilePath({
						canvasId: 'mycanvas',
						success: function(res) {
							console.log(res)
							let path = res.tempFilePath;
							console.log(path)
							uni.uploadFile({
								url: baseUrl + '/minio/uploadFile', 
								filePath: path,
								name: 'file',
								header: {
									'Authorization': 'Bearer ' + token
								},
								success: async (res) => {
									let data = JSON.parse(res.data)
									that.form.signatureImgId = data.data.id
									let letter = await getSignCommitmentLetter({
										signImgId:that.form.signatureImgId,
										socialOrganizationName: that.form.name
									})
									that.form.signatureFileId = letter.data.id
									if(that.isEdit == 2) {
										that.form.status = 1
										let result = await saveDeclarationInfo2(that.form)
										if(result.code == 200) {
											uni.showToast({
												title: '申报成功，等待审核',
												mask: true,
												icon: 'none',
												duration: 3000
											})
											setTimeout(()=> {
												uni.reLaunch({
												  url: '/pages/home/index'
												});
											},2000)
										}
									} else {
										let result = await saveDeclarationInfo(that.form)
										if(result.code == 200) {
											uni.showToast({
												title: '申报成功，等待审核',
												mask: true,
												icon: 'none',
												duration: 3000
											})
											setTimeout(()=> {
												uni.reLaunch({
												  url: '/pages/home/index'
												});
											},2000)
										}
									}
									
									console.log(result)
								},
								fail: (res) => {
									console.log(res)
								}
								
							});


						}
					});
				} else {
					uni.showToast({
						title: '请绘制签名',
						duration: 2000,
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style scoped>
	.mycanvas {
		width: 100%;
		height: 100%;
		background: #F6F8FF;
	}

	.footer {
		position: fixed;
		bottom: 0;
		width: 100%;
		left: 0;
		height: 120rpx;
		width: 100%;
		background-color: #ffffff;
		font-size: 16px;
		/* height: 150upx; */
		display: flex;
		justify-content: space-around;
		align-items: center;
		box-shadow: 0px -2rpx 8rpx 0px rgba(62, 86, 125, 0.2);
		z-index: 9999;
		box-sizing: content-box;
		padding-bottom: constant(safe-area-inset-bottom);
		/* 兼容 iOS < 11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容 iOS >= 11.2 */
	}

	.left,
	.right {
		width: 300rpx;
		height: 88rpx;
		line-height: 88rpx;
		color: #436BE6;
		text-align: center;
		border-radius: 40rpx;
	}

	.left {
		border: 2rpx solid #4D70F8;
	}

	.right {
		border: 2rpx solid #436BE6;
		background: linear-gradient(90deg, #417FFC, #505EEB);
		color: #ffffff;
	}
</style>